package com.pig4cloud.pig.ads.gdt.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.ads.gdt.service.IGdtAdService;
import com.pig4cloud.pig.ads.gdt.service.IGdtCampaignService;
import com.pig4cloud.pig.ads.pig.mapper.gdt.GdtAdMapper;
import com.pig4cloud.pig.ads.service.AdCreativeMaterialService;
import com.pig4cloud.pig.api.gdt.dto.FilteringDto;
import com.pig4cloud.pig.api.gdt.dto.GdtAdDto;
import com.pig4cloud.pig.api.gdt.entity.GdtAd;
import com.pig4cloud.pig.api.util.JsonUtil;
import com.pig4cloud.pig.common.core.exception.CheckedException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 广点通广告服务实现层
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GdtAdServiceImpl extends ServiceImpl<GdtAdMapper, GdtAd> implements IGdtAdService {

	private final IGdtCampaignService gdtCampaignService;

	private final AdCreativeMaterialService adCreativeMaterialService;

	@Value(value = "${gdt_ad_add_url}")
	private String gdtAdAddUrl;

	@Value(value = "${gdt_ad_get_url}")
	private String gdtAdGetUrl;

	/**
	 * 创建广告
	 *
	 * @param gdtAdDto
	 * @return
	 */
	@Override
	public GdtAdDto createGdtAd(GdtAdDto gdtAdDto) {
		try {
			Map<String, Object> param = JsonUtil.parseJSON2Map(JsonUtil.toUnderlineJSONString(gdtAdDto));
			JSONObject jsonObject = gdtCampaignService.createOrGetPostThirdResponse(gdtAdDto.getAccountId(), "createGdtAd", gdtAdAddUrl, param);
			if (null != jsonObject) {
				gdtAdDto.setAdId(jsonObject.getLong("ad_id"));
			}
			return gdtAdDto;
		} catch (Exception e) {
			throw new CheckedException(e.getMessage());
		}

	}


	/**
	 * 拉取并存储广告数据
	 *
	 * @param gdtAdDto
	 */
	@Override
	public void getGdtAdData(GdtAdDto gdtAdDto) {
		List<FilteringDto> filteringDtos = new ArrayList<FilteringDto>();
		if (StringUtils.isNotBlank(gdtAdDto.getAdIds())) {
			filteringDtos.add(new FilteringDto("ad_id", "IN", gdtAdDto.getAdIds().split(",")));
		} else if (null != gdtAdDto.getAdId()) {
			filteringDtos.add(new FilteringDto("ad_id", "EQUALS", gdtAdDto.getAdId().toString().split(",")));
		}

		//增加按广告组过滤
		if (gdtAdDto.getAdgroupId() != null) {
			filteringDtos.add(new FilteringDto("adgroup_id", "EQUALS", String.valueOf(gdtAdDto.getAdgroupId()).split(",")));
		}
		String fields = "campaign_id,adgroup_id,ad_id,ad_name,adcreative_id,adcreative,configured_status,system_status,audit_spec,impression_tracking_url,click_tracking_url,feeds_interaction_enabled,reject_message,is_deleted,is_dynamic_creative,created_time,last_modified_time";
		List<JSONArray> jsonArrayList = gdtCampaignService.getThirdResponse(gdtAdDto.getAccountId(), "getGdtAdData", gdtAdGetUrl, filteringDtos, null, fields, Boolean.TRUE);
		if (CollectionUtils.isNotEmpty(jsonArrayList)) {
			List<GdtAd> gdtAdList = new ArrayList<>();
			jsonArrayList.forEach(result -> {
				List<Map<String, String>> listMap = JSON.parseObject(result.toJSONString(), new TypeReference<List<Map<String, String>>>() {
				});
				String map = JSON.toJSONString(listMap);
				List<GdtAd> list = JSONObject.parseArray(map, GdtAd.class);
				gdtAdList.addAll(list);
			});
			if (CollectionUtils.isNotEmpty(gdtAdList)) {
				gdtAdList.forEach(gdtAd -> {
					gdtAd.setAccountId(gdtAdDto.getAccountId());
					GdtAd entity = this.getOne(Wrappers.<GdtAd>query().lambda().eq(GdtAd::getAdId, gdtAd.getAdId()), false);
					if (entity == null) {
						this.save(gdtAd);
					} else {
						this.update(gdtAd, Wrappers.<GdtAd>query().lambda().eq(GdtAd::getAdId, gdtAd.getAdId()));
					}
				});

				// 更新广告与素材关系信息
				adCreativeMaterialService.batchUpsertTxCreativeMaterial(gdtAdList);
				//baseMapper.batchInsertGdtAd(gdtAdList);
			}

		}
	}
}
